package com.jay.tools.recycler.decoration;

import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

import com.jay.tools.utils.LogUtil;

/**
 * author: tanjianpei
 * date: 2019/9/18 018 10:54
 * description: 适用于StaggeredGridLayoutManager添加头布局并且网格布局左右间距相同情况。
 * 注意：当指定StaggeredGridLayoutManager.VERTICAL时，如果布局中设定了固定宽度，此时recycleView的addItemDecoration将无效，若让其生效item布局必须是wrap_content，
 * 同理当指定StaggeredGridLayoutManager.VERTICAL时，高度的固定值也将无效，需设定为wrap_content
 */
public class SGLItemDecoration extends RecyclerView.ItemDecoration {
    private static final String TAG = "SGLItemDecoration";
    private int spanCount;
    private int spacing;

    /**
     * @param spanCount 列数
     * @param spacing   间距
     */
    public SGLItemDecoration(int spanCount, int spacing) {
        this.spanCount = spanCount;
        this.spacing = spacing;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);

        // 对recycleView添加头布局时
        if (position == 0) {
            outRect.left = 0;
            outRect.right = 0;
            outRect.top = 0;
            outRect.bottom = 0;
        } else {
            // 每一行的列索引
            int column = position % spanCount;
            // 对网格布局生效
            outRect.left = (spacing + column * spacing) / spanCount;
            outRect.right = (spacing + Math.abs(column - 1) * spacing) / spanCount;

            if (position < spanCount) { // top edge
                outRect.top = 0;
            }

//            // 有头布局，所以grid数量要减去1
//            int itemCount = parent.getAdapter().getItemCount() - 1;
//            if (isLastGridRow(position + 1, itemCount, spanCount)) {
//                outRect.bottom = 0;
//            } else {
                outRect.bottom = spacing;
//            }

        }

    }

    /**
     * 是否是最后一行
     *
     * @param position   有头布局需减去1
     * @param itemSize   总的数量，有头布局需减去1
     * @param columnSize 列数
     * @return
     */
    private boolean isLastGridRow(int position, int itemSize, int columnSize) {
        int temp = itemSize % columnSize;
        if (temp == 0 && position >= itemSize - columnSize) {
            return true;
        } else if (position >= itemSize / columnSize * columnSize) {
            return true;
        }
        return false;
    }

}
